package com.cb.web.wasf.sample.web;

import com.cb.web.wasf.WasfController;
import com.cb.web.wasf.State;
import com.cb.web.wasf.sample.model.UniqueConstraintBOException;
import com.cb.web.wasf.sample.model.ProfilBO;
import com.cb.web.wasf.sample.model.ProfilManager;
import com.cb.web.wasf.sample.model.RoleBO;
import com.cb.web.wasf.sample.model.RoleManager;
import com.cb.web.wasf.sample.model.UserBO;
import com.cb.web.wasf.sample.model.UserManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.persist.UnitOfWork;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;

/**
 * @author CBO
 */
@Singleton
public class Controller extends WasfController {

    @Inject
    private RoleManager roleManager;
    @Inject
    private ProfilManager profilManager;
    @Inject
    private UserManager userManager;
    @Inject
    private UnitOfWork unitOfWork;

    @Override
    public void init() throws ServletException {
        unitOfWork.begin();
        try {
            RoleBO userAdministrationRole = roleManager.create(roleManager.getUserAdministrationRole().getName(), roleManager.getUserAdministrationRole().getDescription());
            ProfilBO adminProfil = profilManager.create("Administration", "Administration de l'application");
            ProfilBO exploitProfil = profilManager.create("Exploitation", "Exploitation de l'application");
            ProfilBO editProfil = profilManager.create("Saisie", "Saisie");
            ProfilBO viewProfil = profilManager.create("Consultation", "Consultation");
            adminProfil.getRoles().add(userAdministrationRole);
            UserBO user = userManager.create("login", "password", "firstName", "lastName", "mail@mail.com", true,
                    Arrays.asList(adminProfil, exploitProfil));
            for (int i = 0; i < 10; i++) {
                user = userManager.create("login_" + i, "password_" + i, "firstName_" + i, "lastName_" + i, "mail@mail.com_" + i, true,
                        Arrays.asList(adminProfil, exploitProfil));
            }
        } catch (UniqueConstraintBOException ex) {
            throw new ServletException(ex);
        } finally {
            unitOfWork.end();
        }
    }

    @Override
    public State createInitialState() {
        return new LoginState();
    }
}
